package com.lancoo.answer.ui.ques;

import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.lancoo.answer.R;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.TaskState;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.Ques;
import com.lancoo.answer.model.bean.QuesAudio;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.model.eventBean.AnswerSheetEventBean;
import com.lancoo.answer.util.ExamFontSizeAdjustUtils;
import com.lancoo.answer.util.RichTextUtils;
import com.lancoo.answer.util.SoftInputUtils;
import com.lancoo.answer.util.paperUtils.FragmentCommunicationUtils;
import com.lancoo.answer.util.paperUtils.FragmentLoadUtils;
import com.lancoo.answer.util.paperUtils.SplitViewHeightAdjustTuils;
import com.lancoo.answer.widget.SplitView;
import com.lancoo.answer.widget.audioPlayView.AudioPlayCallBack;
import com.lancoo.answer.widget.audioPlayView.TopicAudioView;
import com.lancoo.answer.widget.audioPlayView.TopicMediaEngine;
import com.lancoo.answer.widget.combinationView.ChildStatisticsView;
import com.rxjava.rxlife.RxLife;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by pengmi on 2021/12/1 13:41
 * Description:上下分页layout fragment
 */
public class SpliteLayoutFragment extends Fragment {

    public static final String TAG = "SpliteLayoutFragment";

    private int currentChildIndex;//当前大题下的小题序号
    private Ques ques;
    private View convertView;
    private ViewPager2 viewPager2;
    private TopicAudioView topicAudioView;
    private int typeIndex;
    private int quesIndex;
    private ChildStatisticsView childStatisticsView;
    private int loadQueseIndex;
    private String sortIndexType;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        convertView = inflater.inflate(R.layout.ev_fragment_splite_layout, container, false);
        return convertView;
    }

    public static Fragment loadFragment(int typeIndex,int queseIndex,int defaultLoadChildIndex,int defaultLoaditemIndex){
        Bundle mBundle=new Bundle();
        mBundle.putInt(AnswerConstant.KEY_TYPEINDEX,typeIndex);
        mBundle.putInt(AnswerConstant.KEY_QUESINDEX,queseIndex);
        mBundle.putInt(AnswerConstant.KEY_LOADCHILDINDEX,defaultLoadChildIndex);
        mBundle.putInt(AnswerConstant.KEY_LOADITEMINDEX,defaultLoaditemIndex);
        SpliteLayoutFragment spliteLayoutFragment=new SpliteLayoutFragment();
        spliteLayoutFragment.setArguments(mBundle);
        return spliteLayoutFragment;
    }

    @Override
    public void onPause() {
        super.onPause();
        pauseQuesAudioPlay();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void initView(View view){
        if(getArguments()==null||getContext()==null||
                ConstantBean.Companion.getConstantExamBean()==null){
            return;
        }
        adjustFontSize();
        loadQueseIndex = getArguments().getInt(AnswerConstant.KEY_LOADCHILDINDEX);
        List<Type> kindBeanListk = ConstantBean.Companion.getConstantExamBean().getTypeList();
        typeIndex = getArguments().getInt(AnswerConstant.KEY_TYPEINDEX);
        quesIndex = getArguments().getInt(AnswerConstant.KEY_QUESINDEX);
        if(kindBeanListk==null||kindBeanListk.get(typeIndex).getQuesList()==null){
            return;
        }
        List<Ques> quesList = kindBeanListk.get(typeIndex).getQuesList();
        if(quesList==null|| quesIndex >=quesList.size()){
            return;
        }
        ques = quesList.get(quesIndex);
        childStatisticsView = view.findViewById(R.id.child_statistics_view);
        childStatisticsView.setQues(ques);
        if (ques.getTypeNo().equals("x")||ques.getTypeNo().equals("L")){
            childStatisticsView.setVisibility(View.GONE);
        }
        viewPager2 = view.findViewById(R.id.viewPager2);
        viewPager2.setAdapter(new FragmentStateAdapter(this)    {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                if(ques==null||getArguments()==null){
                    return new WaitToDockFragment();
                }
                int loadItemIndex = getArguments().getInt(AnswerConstant.KEY_LOADITEMINDEX);
                return FragmentLoadUtils.loadChildFragment(ques, typeIndex, quesIndex,position, loadQueseIndex,loadQueseIndex,loadItemIndex);
            }

            @Override
            public int getItemCount() {
                if (ques.getTypeNo().equals("L")){
                    return 1;
                }else {
                    return ques.getChildList() == null ? 0 : ques.getChildList().size();
                }
            }
        });
        sortIndexType = ques.getChildList().get(0).getSortIndexType();
        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if(getContext()==null){
                    return;
                }
                int tempIndex=currentChildIndex;
                currentChildIndex =position;
                childStatisticsView.updateChildIndex(currentChildIndex);
                Fragment fragment = getChildFragmentManager().findFragmentByTag(TAG);
                FragmentCommunicationUtils.switchTestQuesionToEvent(typeIndex,quesIndex,
                        position,false,1);
//                if(TextUtils.equals("1", sortIndexType)){
//                    return;
//                }else{
//
//                }
                if(tempIndex==position){
                    return;
                }
                FragmentCommunicationUtils.synchroTopFragment(fragment, currentChildIndex);
                if(getActivity()!=null){
                    SoftInputUtils.hideSoftInput(getActivity());
                }
            }
        });
        if(ques.getChildList()!=null&&loadQueseIndex !=-1&& loadQueseIndex <ques.getChildList().size()){
            Single.timer(200, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .as(RxLife.as(SpliteLayoutFragment.this, Lifecycle.Event.ON_PAUSE))
                    .subscribe(o -> {
                        viewPager2.setCurrentItem(loadQueseIndex);
                    }, throwable -> {

                    });

        }
        topicAudioView = view.findViewById(R.id.topicAudioView);
        if(ques.getAudioList()!=null&&ques.getAudioList().size()>0){
            if(!TextUtils.isEmpty(ques.getQuesIndexText())&&
                    !TextUtils.isEmpty(Html.fromHtml(ques.getQuesIndexText()).toString().trim())){
                TextView tv_listenPassage=view.findViewById(R.id.tv_listen_passage);
                tv_listenPassage.setText(RichTextUtils.getQueseAnalysisCharSequence(Html.fromHtml(ques.getQuesIndexText())));
                tv_listenPassage.setVisibility(View.VISIBLE);
            }
            view.findViewById(R.id.tv_listen_passage);
            topicAudioView.setVisibility(View.VISIBLE);
            String url=ques.getAudioList().get(0).getPath();
            List<String> audioList = new ArrayList<>();
            int index=0;
            for (QuesAudio audio:ques.getAudioList()){
                if(audioList.size()==0&&TextUtils.isEmpty(audio.getPath())){
                    continue;
                }
                String path = audio.getPath();
                if(path!=null&&path.endsWith("secblankaudio.mp3")){
                    try {
                        String substring = path.substring(path.lastIndexOf("/")+1);
                        String split0=substring.split(".")[0];
                        audioList.add(split0);
                        continue;
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
                if (audio.getType()==2||audio.getType()==1){
                    if(index==ques.getAudioList().size()-1){
                        break;
                    }
                    if (audio.getDuration()>0){
                        audioList.add(audio.getDuration()+"");  //当前是时间间隔
                    }
                }else {
                    audioList.add(audio.getPath());
                }
                index++;
            }
            TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
            if(taskControlBean==null){
                return;
            }
            int trainSence=taskControlBean.getTrainSence();
            TaskState taskState = ConstantBean.Companion.getTaskState();
            boolean enable=taskControlBean.getEnableAutoPlay()==1;
            if(!enable){
                topicAudioView.setConfig(new TopicAudioView.Config(ques.getQuesIndexText(),url,
                        taskControlBean.getEnableAutoPlay()==1,
                        (trainSence!=0&&taskState==TaskState.TRAINING),
                        !(trainSence!=0&&taskState==TaskState.TRAINING),false,null,1,
                        new TopicMediaEngine(getContext().getApplicationContext()),audioList));
            }else{
                topicAudioView.setConfig(new TopicAudioView.Config("",url,
                        true,
                        false,false,false,null,1,
                        new TopicMediaEngine(getContext().getApplicationContext()),audioList));
            }
            topicAudioView.setCallBack(new AudioPlayCallBack(){
                @Override
                public void onAudioPlay() {
                    super.onAudioPlay();
                    FragmentCommunicationUtils.closeAllMediaPlay(SpliteLayoutFragment.this);
                }
            });
            if (ConstantBean.Companion.getTaskControlBean().getTrainSence()!=0
                    &&getActivity()!=null){
                getActivity().getLifecycle().addObserver(topicAudioView);
                if(taskControlBean.isQuesAudioPlaying()){
                    updateExamPlayState(true);
                }
            }else {
                getLifecycle().addObserver(topicAudioView);
            }
        }
        SplitView splitView=view.findViewById(R.id.split_view);
        SplitViewHeightAdjustTuils.splitViewDefaultLoadHeight(ques,splitView);
        loadQuesBodyFragment(loadQueseIndex);
        FragmentCommunicationUtils.changeDefaultChildIndex(this,loadQueseIndex);
    }

    /**
     * 加载大题题干内容
     */
    private void loadQuesBodyFragment(int loadQuesIndex){
        if(getArguments()==null){
            return;
        }
        FragmentManager childFragmentManager = getChildFragmentManager();
        FragmentTransaction fragmentTransaction = childFragmentManager.beginTransaction();
        int anInt = getArguments().getInt(AnswerConstant.KEY_LOADITEMINDEX);
        Fragment fragment=FragmentLoadUtils.loadQuesBodyFragment(ques, typeIndex, quesIndex,0,loadQuesIndex,anInt);
        fragmentTransaction.replace(R.id.framelayout_topicBody,fragment,TAG);
        fragmentTransaction.commitAllowingStateLoss();
    }

    /**
     * 暂停音频播放
     */
    public void pauseQuesAudioPlay(){
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean==null){
            return;
        }
        if (topicAudioView!=null){
            if(taskControlBean.getEnableAutoPlay()==1){
                topicAudioView.pauseTimeer();
            }else{
                topicAudioView.pause();
            }
        }
    }

    /**
     * 获取当前大题下的小题序号
     * @return 小题序号
     */
    public int getCurrentChildIndex(){
        if(TextUtils.equals("L",ques.getTypeNo())){
            if(viewPager2!=null){
                long itemId = viewPager2.getAdapter().getItemId(0);
                Fragment fragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
                return FragmentCommunicationUtils.getCurrentQuesChildIndex(fragment);
            }

        }
        return currentChildIndex;
    }

    /**
     * 获取当前大题下的答题点序号
     * @return 答题点序号
     */
    public int getCurrentItemIndex(){
        if(viewPager2!=null){
            int currentItem = viewPager2.getCurrentItem();
            if(viewPager2.getAdapter()==null){
                return 0;
            }
            if(currentItem==0){//综合匹配特殊处理
                Fragment fragment = getChildFragmentManager().findFragmentByTag(TAG);
                if(TextUtils.equals("k",ques.getTypeNo())){
                    return FragmentCommunicationUtils.getCurrentQuesItemIndex(fragment);
                }
            }
            long itemId = viewPager2.getAdapter().getItemId(currentItem);
            Fragment fragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
            return FragmentCommunicationUtils.getCurrentQuesItemIndex(fragment);
        }
        return 0;
    }

    /**
     * 跳转到指定小题 ，指定答题点
     * @param childIndex 小题序号
     * @param itemIndex 答题点序号
     * @param jumpFrom 跳转来源 0-答题卡点击跳转 3-复合写作点击试题题干切换小题，2-篇章翻译点击分句题干切换，1-填空题弹窗作答切题，4-其他跳转
     */
    public void jumpToAimChildFragment(int childIndex,int itemIndex,int jumpFrom){
        if(viewPager2!=null){
            if(TextUtils.equals(ques.getGenreID(),"65")){//特殊题型适配
                long itemId = viewPager2.getAdapter().getItemId(0);
                Fragment fragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
                if(TextUtils.equals(sortIndexType,"0")){
                    FragmentCommunicationUtils.jumpToItemFragment(fragment,childIndex,childIndex);
                }else{
                    FragmentCommunicationUtils.jumpToItemFragment(fragment,childIndex,itemIndex);
                }
            }else{
                //下分屏fragment
                Child child = ques.getChildList().get(childIndex);
                String sortIndexType = child.getSortIndexType();
                viewPager2.setCurrentItem(childIndex, true);
                long itemId = viewPager2.getAdapter().getItemId(childIndex);
                Fragment fragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
                if(TextUtils.equals(sortIndexType,"0")){//按照小题作答
                    if(child.getItemList().size()>1){//一题多空
                        FragmentCommunicationUtils.jumpToItemFragment(fragment,childIndex,itemIndex);
                    }else{
                        FragmentCommunicationUtils.jumpToItemFragment(fragment,childIndex,childIndex);
                    }
                }else{//按照答题点作答
                    FragmentCommunicationUtils.jumpToItemFragment(fragment,childIndex,itemIndex);
                }

                //上分屏fragment
                Fragment topFragment = getChildFragmentManager().findFragmentByTag(TAG);
                if(topFragment!=null){
                    FragmentCommunicationUtils.jumpToItemFragment(topFragment,childIndex,itemIndex);
                }
            }
        }
    }

    /**
     * 跳转到指定小题 ，指定答题点
     * @param childIndex 小题序号
     * @param itemIndex 答题点序号
     * @param jumpFrom 跳转来源 0-答题卡点击跳转 3-复合写作点击试题题干切换小题，2-篇章翻译点击分句题干切换，1-填空题弹窗作答切题，4-其他跳转
     */
    public void jumpToAimChildFragment(int quesIndex,int childIndex,int itemIndex,int jumpFrom){
        if(quesIndex==this.quesIndex){
            jumpToAimChildFragment(childIndex,itemIndex,jumpFrom);
        }else{
            AnswerSheetEventBean answerSheetEvent=new AnswerSheetEventBean();
            answerSheetEvent.setTypeIndex(typeIndex);
            answerSheetEvent.setQuesIndex(quesIndex);
            answerSheetEvent.setChildIndex(childIndex);
            answerSheetEvent.setItemIndex(itemIndex);
            answerSheetEvent.setEventType(1);
            EventBus.getDefault().post(answerSheetEvent);
        }
    }

    /**
     * 跳转到指定答题点序号
     * @param itemIndex 小题序号
     */
    public void jumpToAimItemFragment(int itemIndex){
        if(viewPager2!=null&&viewPager2.getAdapter()!=null){
            long itemId = viewPager2.getAdapter().getItemId(currentChildIndex);
            Fragment fragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
            FragmentCommunicationUtils.jumpToItemFragment(fragment,0,itemIndex);
        }
    }

    /**
     * 自动进入下一个小题作答
     * @return 是否到尾了
     */
    public boolean autoToNextChild(){
        if(ques.getChildList()==null){
            return false;
        }
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        TaskState taskState = ConstantBean.Companion.getTaskState();
        if(taskControlBean==null){
            return false;
        }
        if(taskControlBean.getTrainSence()!=0&&taskControlBean.isQuesAudioPlaying()
                &&taskState==TaskState.TRAINING){
            return false;
        }
        if(!taskControlBean.isEnableAutoSkipAnswer()){
            return false;
        }
        if(currentChildIndex <ques.getChildList().size()-1){
            if(viewPager2!=null){
                viewPager2.setCurrentItem(currentChildIndex +1);
            }
            return false;
        }else{
            return !taskControlBean.isQuesAudioPlaying();
        }
    }

    /**
     * 软键盘弹起，SplitView自动撑大下方布局
     */
    public void updateSplitLayout(boolean isShow){
        if(convertView==null||!isShow){
            return;
        }
        SplitView splitView = convertView.findViewById(R.id.split_view);

        Single.timer(250, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        SplitViewHeightAdjustTuils.splitViewLoadHeightToKeyBoard(ques,splitView);
                    }
                }, throwable -> {

                });
    }

    public void initLayout(){
        if(convertView==null){
            return;
        }
        SplitView splitView = convertView.findViewById(R.id.split_view);
        Single.timer(250, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        splitView.initLayout(0.5f);
                    }
                }, throwable -> {

                });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 自动开始播放大题音频
     */
    public void audioPlayAudio(){
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean==null){
            return;
        }
        int enableAnwer = taskControlBean.getEnableAnwer();
        int enableAutoPlay = taskControlBean.getEnableAutoPlay();
        if (topicAudioView!=null){
            topicAudioView.changeEnableState(enableAnwer==1);
            topicAudioView.startTimeCountAndPlay(enableAutoPlay==1);
        }
    }

    /**
     * 更新小题作答倒计时
     * @param countdown 秒
     * @param isShow boolean
     */
    public void updateChildCountdown(int countdown,boolean isShow){
        if(childStatisticsView!=null){
            childStatisticsView.updateAnswerCountdown(countdown,isShow);
        }
    }

    /**
     * 更新音频播放状态 考试专用
     * @param isPlaying boolean
     */
    public void updateExamPlayState(boolean isPlaying){
        if (topicAudioView!=null){
            if(isPlaying){
                topicAudioView.play();
            }else{
                topicAudioView.stopPlayTestingAnimation();
            }
        }
    }

    public void disableVpScorll(){
        if(viewPager2!=null){
            viewPager2.setUserInputEnabled(false);

            Single.timer(250, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .as(RxLife.as(this))
                    .subscribe(aLong -> viewPager2.setUserInputEnabled(true), throwable -> {

                    });
        }
    }

    public void reposition(){
        if(currentChildIndex==0){
            return;
        }
        if(viewPager2!=null){
            currentChildIndex=0;
            viewPager2.setCurrentItem(0);
        }
    }

    public void adjustFontSize(){
        if(convertView==null){
            return;
        }
        TextView textView = convertView.findViewById(R.id.tv_listen_passage);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView,15);
        ChildStatisticsView childStatisticsView = convertView.findViewById(R.id.child_statistics_view);
        childStatisticsView.adjustFontSize();
        Observable.timer(100,TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(aLong -> {;
                    Log.e("qwewq","splitView requestLayout");
                    SplitView splitView = convertView.findViewById(R.id.split_view);
                    splitView.invalidate();
                }, throwable -> {

                });
    }

    public void markQuestion(){
        if(viewPager2==null){
            return;
        }
        int currentItem = viewPager2.getCurrentItem();
        long itemId = viewPager2.getAdapter().getItemId(currentItem);
        FragmentManager childFragmentManager = getChildFragmentManager();
        Fragment fragmentByTag = childFragmentManager.findFragmentByTag("f" + itemId);
        FragmentCommunicationUtils.markQuestion(fragmentByTag);
    }
}
